package jnpf.engine.util;

import jnpf.engine.custom.constants.BasicActivitiConstants;
import org.flowable.engine.HistoryService;
import org.flowable.engine.ManagementService;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.TaskService;
import org.flowable.task.api.Task;
import org.flowable.task.service.impl.persistence.entity.TaskEntity;
import org.flowable.variable.api.history.HistoricVariableInstance;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author LoveMyOrange
 * @create 2022-01-06 14:13
 */
@Component
public class ActivitiDataBaseUtils {

    @Resource
    private HistoryService historyService;
    @Resource
    private RepositoryService repositoryService;
    @Resource
    private TaskService taskService;
    @Resource
    private ManagementService managementService;

    /**
      * @param processInstanceId
     * @return
     */
   public String getApplyUserIdVariable(String processInstanceId){
       HistoricVariableInstance historicVariableInstance = historyService.createHistoricVariableInstanceQuery().processInstanceId(processInstanceId).variableName(BasicActivitiConstants.startEventInitiator).singleResult();
       return historicVariableInstance.getValue().toString();
   }

    /**
     * @return
     */
   public Task getTaskByProcessInstanceIdAndTaskDefinitionKey(String processInstanceId, String taskDefinitionKey){
       Task task = taskService.createNativeTaskQuery().sql("SELECT ID_, ASSIGNEE_  FROM " +
               managementService.getTableName(TaskEntity.class) + " WHERE PROC_INST_ID_ = #{processInstanceId} AND TASK_DEF_KEY_ = #{taskDefinitionKey}")
               .parameter("processInstanceId", processInstanceId)
               .parameter("taskDefinitionKey", taskDefinitionKey)
               .list().get(0);
       return task;
   }
}
